package com.odm.communitymanage.ui.help

import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.net.Uri
import android.view.View
import android.widget.ImageView
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import com.bumptech.glide.Glide
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseFragment
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.NetCallBack
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.util.GlideUtils
import com.odm.communitymanage.util.Utils
import com.rxjava.rxlife.lifeOnMain
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_post_idle.*
import kotlinx.android.synthetic.main.fragment_post_seek_help.*
import rxhttp.wrapper.param.RxHttp

/**
 * @description: 发布求助 页面
 * @author: ODM
 * @date: 2020/4/14
 */
class PostHelpFragment  : BaseFragment() {

    var disposable : Disposable?= null

    var photoUris: MutableList<Uri> ? = null


    override fun onDestroyView() {
        super.onDestroyView()
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
    }


    override fun initViews() {
        //添加图片
        btnPostSeekHelpPhoto?.setOnClickListener {
            //跳转页面选择图片，当选择了图片后，依次让iv1,iv2,iv3 设为Visible，iv3也可见后将添加图片按钮设为inVisible！
            Matisse.from(this)
                .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.WEBP))
                .countable(true)
                .maxSelectable(3)
                .capture(true)
                .captureStrategy( CaptureStrategy(true,"com.odm.communitymanage.fileprovider"))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.55f)
                .imageEngine(GlideEngine())
                .showPreview(false)
                .forResult(Constants.REQUEST_IMAGE_CODE)
        }

        //提交 求助 信息
        btnPostHelp?.setOnClickListener {
            val userName = etContactName_PostHelp?.text.toString()
            val phone  = etPhoneNumber_PostHelp?.text.toString()
            val content = etContent_PostHelp?.text.toString()
            val remarks = etRemark_PostHelp?.text.toString()
            postSeekHelpInfo(content,remarks,userName,phone,photoUris)
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //加载从 图库中选择的图片，每次为多张或单张，最多放入3张
        if (requestCode == Constants.REQUEST_IMAGE_CODE && data != null) {
            val result = Matisse.obtainResult(data)
            val uriList: MutableList<Uri>? = result
            uriList?.let {
                for (uri in uriList) {
                    var target : ImageView?= null
                    if (ivSeekHelpPhoto_1.visibility != View.VISIBLE) {
                        target = ivSeekHelpPhoto_1
                    } else if (ivSeekHelpPhoto_2.visibility != View.VISIBLE) {
                        target = ivSeekHelpPhoto_2
                    } else if (ivPostSeekHelpPhoto_3.visibility != View.VISIBLE) {
                        target = ivPostSeekHelpPhoto_3
                        btnPostSeekHelpPhoto.visibility = View.INVISIBLE
                    }
                    target?.let {
                        target.visibility = View.VISIBLE
                        GlideUtils.getInstance()
                            .loadImageUri(requireContext(),
                                            uri ,
                                            target)
                        //添加进上传图片的Uri列表
                        photoUris?.add(uri)
                    }
                }

            }
        }
    }




    override fun getLayoutId(): Int {
        return R.layout.fragment_post_seek_help
    }

    /**
     * 提交 求助数据 post请求
     *
     * @param content String?
     * @param remarks String?
     * @param userName String
     * @param phone String
     * @param photos MutableList<Uri>?
     */
    private fun postSeekHelpInfo(content : String?, remarks:String?,
                                 userName:String, phone:String,
                                 photos:MutableList<Uri>?)       {

        if(content == ""){
            ToastUtils.showShort("求助内容不可为空")
            return
        }
        if(photos?.isEmpty() == true){
            ToastUtils.showShort("请选择合适的图片")
            return
        }
        //当联系人为 空，则默认提交 当前用户名
        val name: String = if(userName == "") {
            SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_NAME)
        }else{
            userName
        }
        val phoneNumber = if(phone == ""){
            SPUtils.getInstance(Constants.SP_USER).getString(Constants.USER_PHONE_NUMBER)
        }else{
            phone
        }

        val param = RxHttp.postForm(ApiService.POST_SEEK_HELP)
            .add("content",content)
            .add("username",name)
            .add("phone",phoneNumber)
            .add("remarks",remarks)
        //添加文件
        photos?.let {
            for(uri in photos){
                val photo = Utils.getPhotoFileByUri(uri  ,true)
                param.addFile("file",photo)
            }
        }
        disposable = param.asClass(NetCallBack::class.java)
            .lifeOnMain(this)

            .subscribe({
                if(it.code != 1){
                    ToastUtils.showShort(it.message)
                }else {
                    //上传成功
                    showSuccessSnack(getString(R.string.post_success))
                    //返回上一页
                    pop()
                }
            },{
                //出现异常
                ToastUtils.showShort(it.message)
            })
    }


}